<?php

namespace Frieza\Modules\Live\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Live\LiveRoomExtend as mLiveRoomExtend;
use Doraemon\model\Live\LiveVideo as mLiveVideo;
use Doraemon\service\Live\AdmLive;
use Doraemon\tools\BlockType;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Live\LiveRelaContent;
use Doraemon\model\Article as dbArticle;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\service\Live\AdmColumn;
use Doraemon\model\Live\LiveRoom as mLiveRoom;
use Doraemon\model\Member;
use Doraemon\model\Live\LiveLottery as mLottery;
use Doraemon\service\Live\LiveLottery as sLottery;

class BackController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        Admin::script($this->setScript());

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $condition = $this->_index_condition($request);
        if($condition['is_empty']){
            $result = [
                'list' => [],
                'total' => 0
            ];
        }else{
            $where = $condition['condition'];
            $where['LIMIT'] = [
                ($page - 1) * $pageSize,
                $pageSize
            ];
            $where['ORDER'] = ['id' => 'DESC'];
            $where['video_status'] = mLiveVideo::STATUS_NORMAL;
            $result = AdmLive::getBackList($where);
        }
        if($result['list']){
             $room_ids = array_column($result['list'] , 'room_id');
             $relaContent = LiveRelaContent::selectByWhere(['room_id' => $room_ids , 'rela_status' => LiveRelaContent::STATUS_NORMAL]);
             $hash_rela_content = [];
             if($relaContent && is_array($relaContent)){
                 $obj_ids = array_column($relaContent , 'obj_id');
                 $info =   dbArticle::getArticleByIds($obj_ids);
                 $info = array_combine(array_column($info , 'aid') , $info);
                 foreach ($relaContent as $val){
                     if($info[$val['obj_id']]){
                         $hash_rela_content[$val['room_id']]['rela_id'] = $val['id'];
                         $hash_rela_content[$val['room_id']]['obj_id'] = $val['obj_id'];
                         $hash_rela_content[$val['room_id']]['article_title'] = $info[$val['obj_id']]['title'];
                     }
                 }
             }
             foreach ($result['list'] as &$val){
                 $val['article_id'] = $hash_rela_content[$val['room_id']]['obj_id'] ? : '';
                 $val['article_title'] = $hash_rela_content[$val['room_id']]['article_title']  ? : '';
                 $val['rela_id'] =  $hash_rela_content[$val['room_id']]['rela_id'] ? : 0;
             }
        }
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);
        //直播栏目列表
        $column_list= AdmColumn::columnList();
        $column_list[0] = '无栏目';
        //直播栏目列表
        Admin::script(self::transScript());
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel,$column_list) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) use ($column_list) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                      //  $filter->equal('room_id', '房间id');
                        $filter->dropDown('Find', [
                            'room_id' => '房间id',
                            'uid' => 'uid',
                            'nick' => '用户昵称',
                            'room_title' => "直播标题"
                        ]);
                    });
                    $filter->column(1 / 2, function ($filter) use ($column_list) {
                        $filter->equal('room_column', '直播栏目')->select($column_list);
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(40);
                $grid->column('room_id', '房间ID')->width(60);
                $grid->column('room_title', '直播标题')->width(100);
                $grid->column('uid', '直播用户')->display(function () {
                    return '<p>' . $this->uid . '</p>' . '<p>' . $this->user_nick . '</p>';
                })->width(80);
                $grid->column('hot', '热度')->width(100)->editable();
                $grid->column('follow', '关注数')->width(100);
                $grid->column('msg_count', '评论数')->width(100);
                $grid->column('total_request', '请求数')->width(100);
                $grid->column('pop_count', '浮框曝光量')->width(100);
                $grid->column('like_count', '点赞数')->width(100);
                $grid->column('stream_id', '直播流')->width(120);
                $grid->column('duration', '时长')->width(120);
                $status = [
                    'on' => [
                        'value' => mLiveVideo::IS_SHOW_POP,
                        'text' => '是'
                    ],
                    'off' => [
                        'value' => mLiveVideo::NOT_SHOW_POP,
                        'text' => '否'
                    ],
                ];
                $grid->column('is_show_pop', '是否展示广告牌')->switchToggle($status);

                $status = [
                    'on' => [
                        'value' => mLiveVideo::IS_INDEX,
                        'text' => '是'
                    ],
                    'off' => [
                        'value' => mLiveVideo::NOT_INDEX,
                        'text' => '否'
                    ],
                ];

                $grid->column('is_live_index', '是否加入直播指数')->switchToggle($status);

                $grid->column('article_id', '关联文章')->display(function() {
                    if($this->article_id){
                        $display[] =  '<p style="white-space:nowrap">整屋id:'.$this->article_id.'</p>';
                        $display[] =  '<p style="white-space:nowrap">标题:'.$this->article_title.'</p>';
                    }
                    $display[] =  '<span style="display:none">标题:'.$this->is_show.'</span>';
                    if($this->is_show){
                        $live_url ='/admin/live/index/backList/setContent/'.$this->room_id;
                        $display[] = '<a href="javascript:layer.open({
                            type: 2,
                            title: \'编辑\',
                            maxmin: true,
                            area: [\'400px\', \'500px\'],
                            content: \'' . $live_url . '\'
                        });"    data-score="80" class="label  grade_2 label-info"> 编辑整屋  </a><br/>';
                    }

                    if($this->article_id){
                        $display[] = '<p><a class="delcontent label  label-warning" data-id="' . $this->rela_id . '"   href="javascript:void(0);">删除</a></p>';
                    }
                    return implode('<br/>', $display);

                })->width(200);;
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $url = url('/admin/live/index/videoPlay/' . $actions->row->id);
                    //$url = Hhzurl::h5ShareLive($actions->row->id,true);
                    if ($actions->row->trans_task_id) {
                        if ($actions->row->mp4_url) {
                            $downUrl = $actions->row->mp4_url . '?download_name=' . $actions->row['room_id'] ."_".$actions->row['room_title']. '_' . date('YmdHis') . '_' . $actions->row['file_id'] . '.mp4';
                            $actions->prepend('<a class="fa fa-download" href="' . $downUrl . '" target="_blank">mp4下载</a>');
                            $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'mp4预览\',
                                maxmin: true,
                                area: [\'360px\', \'640px\'],
                                content: \'' . $actions->row->mp4_url . '\'
                            });">mp4预览</a>');
                        } else {
                            $actions->prepend('<a class="fa fa-refresh trans-task" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>刷新任务</a>');
                            $actions->append('<a class="fa fa-sun-o trans-reset-task" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>重置任务</a>');
                            //$actions->prepend('<a class="fa fa-refresh trans-video" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>重转mp4</a>');
                        }
                    } else {
                        $actions->prepend('<a class="fa fa-refresh trans-video" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>转码mp4</a>');
                    }
                    $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'360px\', \'640px\'],
                                content: \'' . $url . '\'
                            });">HLS预览</a>');

                    $url = url('/admin/live/lottery/' . $actions->row->room_id);
                    $actions->prepend('<a class="fa fa-github-alt lottery" href="'.$url.'" target="_blank" )>查看中奖名单</a>');
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->add('回看列表', $gridList->render(), true);
        $tab->addLink('转码列表', url('/admin/live/transmp4list'), false);
        $tab->addLink('问题列表', url('/admin/live/index/question'), false);
        return $content->header('回看列表')->breadcrumb(
            ['text' => '回看列表'])
            ->row($tab);
    }


    public function lotteryList(Request $request , Content $content , $room_id)
    {

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $where= [];
        $where['room_id'] = $room_id;
        $where['lottery_status'] = mLottery::SUCC_STATUS;
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = mLottery::getListByWhere($where);
        foreach ($list as &$val){
            $condition = json_decode($val['lottery_condition'] , true);
            $val['prize_name'] = $condition['prize_name'];
            $val['prize_num'] = $condition['prize_num'];
            $draw_user_info =  sLottery::getDrawUids($val['prize_id'] , $val['series_id']);
            $val['draw_uids'] = $draw_user_info;
        }

        $result['list'] = $list;
        unset($where['LIMIT']);
        $result['total'] = count($list);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(40);
                $grid->column('prize_name', '奖品名称')->width(80);
                $grid->column('prize_num', '奖品数量')->width(100);
                $grid->column('draw_uids', '中奖名单')->display(function (){
                    $display='';
                    foreach($this->draw_uids as $user){
                        $display .= '<p>uid:' . $user['uid'].'   nick:' .$user['nick']  . '</p>';
                    }
                    return $display;
                })->width(100);
                $grid->disableActions();

            }
        );
        $tab = new Tab();
        $tab->add('中奖列表', $gridList->render(), true);
        return $content->header('中奖列表')
            ->row($gridList->render());



    }



    public function trans(Request $request, $id = 0)
    {
        try {
            $result = AdmLive::TransLiveVideo($id);
            if ($result) {
                $success = [
                    'code' => 1,
                    'title' => 'id ：' . $id . ' 创建转码任务成功'
                ];
            } else {
                $success = [
                    'code' => 0,
                    'title' => 'id ：' . $id . ' 创建转码任务失败'
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'code' => 0,
                'title' => '创建失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ];
        }
        return response()->json($success);
    }


    public function resetTrans(Request $request, $id = 0)
    {
        try {
            $result = mLiveVideo::updateData(['trans_task_id' => ''] , ['id' => $id]);
            if ($result) {
                $success = [
                    'code' => 1,
                    'title' => 'id ：' . $id . ' 创建转码任务成功'
                ];
            } else {
                $success = [
                    'code' => 0,
                    'title' => 'id ：' . $id . ' 创建转码任务失败'
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'code' => 0,
                'title' => '创建失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ];
        }
        return response()->json($success);
    }





    public function transmp4list(Request $request , Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['id' => 'DESC'];

        $list = AdmLive::getTransVideoList();

        $gridModel = new pGridDataModel($list, count($list), [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                $grid->disablePagination();
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(70);
                $grid->column('room_id', '房间ID')->width(70);
                $grid->column('room_title', '直播标题')->width(150);
                $grid->disableActions();
            }
        );
        $tab = new Tab();
        $tab->addLink('回看列表', url('/admin/live/index/backList'), false);
        $tab->add('转码列表', $gridList->render(), true);
        $tab->addLink('问题列表', url('/admin/live/index/question'), false);
        return $content->header('问题列表')->breadcrumb(
            ['text' => '问题列表'])
            ->row($tab);

    }

    public function transTask(Request $request, $id = 0)
    {
        try {
            $result = AdmLive::changeTransVideoData($id);
            if ($result) {
                $success = [
                    'code' => 1,
                    'title' => 'id ：' . $id . ' 转码任务重置成功'
                ];
            } else {
                $success = [
                    'code' => 0,
                    'title' => 'id ：' . $id . ' 转码任务重置失败'
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'code' => 0,
                'title' => '转码任务获取失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ];
        }
        return response()->json($success);
    }

    private function transScript()
    {
        return <<<SCRIPT
        $('.trans-video').unbind('click').click(function(){
            let url = '/admin/live/index/backList/trans/' +  $(this).data('id')
            let params = {}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg('创建转码任务成功,稍后页面列表刷新任务');
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        
         $('.trans-reset-task').unbind('click').click(function(){
            let url = '/admin/live/index/backList/resetTrans/' +  $(this).data('id')
            let params = {}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg('重置任务成功');
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        $('.trans-task').unbind('click').click(function(){
            let url = '/admin/live/index/backList/transTask/' +  $(this).data('id')
            let params = {}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        
SCRIPT;
    }


    public function question(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        if (isset($request['room_id']) && ($request['room_id'] > 0)) {
            $where['room_id'] = $request['room_id'];
        } else if (isset($request['uid']) && ($request['uid'] > 0)) {
            $where['uid'] = $request['uid'];
        }

        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['id' => 'DESC'];
        $result = AdmLive::getQuestion($where);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);
        //直播栏目列表
        $column_list= AdmColumn::columnList();
        $column_list[0] = '无栏目';
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('room_id', '房间id');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '直播uid');
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(70);
                $grid->column('room_id', '房间ID')->width(70);
                $grid->column('room_title', '直播标题')->width(150);
                $grid->column('uid', '用户')->display(function () {
                    return '<p>' . $this->uid . '</p>' . '<p>' . $this->user_nick . '</p>';
                });
                $grid->column('question', '问题')->width(200);
                $grid->column('point', '消耗积分')->width(100);
                $grid->disableActions();
            }
        );
        $tab = new Tab();
        $tab->addLink('回看列表', url('/admin/live/index/backList'), false);
        $tab->addLink('转码列表', url('/admin/live/transmp4list'), false);
        $tab->add('问题列表', $gridList->render(), true);
        return $content->header('问题列表')->breadcrumb(
            ['text' => '问题列表'])
            ->row($tab);
    }

    public static function changeHot(Request $request, Content $content, $id)
    {
        $name = $request->input('name', '');
        $value = $request->input('value', 0);
        $params = $request->all();
        try {
            $info = mLiveVideo::getByWhere(['id' => $id]);
            $roomId = $info ? $info['room_id'] : 0;
            if ($roomId && $name == 'hot' && $value) {
                mLiveRoomExtend::updateData(['hot' => $value], ['room_id' => $roomId]);
                return response()->json([
                    'status' => true,
                ]);

            } elseif( isset($params['is_show_pop'])){
                $data = [];
                $data['is_show_pop'] =    $params['is_show_pop']  == "on" ? 1 : 0;
                mLiveVideo::updateData($data , ['id' => $id]);
                return response()->json([
                    'status' => true,
                ]);

            }elseif( isset($params['is_live_index'])){
                $data = [];
                $data['is_live_index'] =    $params['is_live_index']  == "on" ? 1 : 0;
                mLiveVideo::updateData($data , ['id' => $id]);
                return response()->json([
                    'status' => true,
                ]);
            }else {
                throw new \Exception('参数错误或则不存在的直播');
            }
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }


    public function videoPlay(Request $request, $id)
    {
        $info = mLiveVideo::getByWhere(['id' => $id]);
        return view('live::video', [
            'fileId' => $info['file_id'],
            'videoUrl' => $info['video_url'],
        ]);
    }

    public function _index_condition($request)
    {
        $response = [];
        $room_ids = [];
        $is_empty = false;
        if (isset($request['room_id']) && ($request['room_id'] > 0)) {
            $room_ids[]= $request['room_id'];
        }else{
            if (isset($request['room_title']) && ($request['room_title'])) {
                $room_ids =  mLiveRoom::selectByWhere(['room_title[~]' => $request['room_title']],'room_id');
                if(empty($room_ids)){
                    $is_empty  = true;
                }
            }

            if (isset($request['uid']) && ($request['uid'])) {
                $room_ids =  mLiveRoom::selectByWhere(['uid' => $request['uid']],'room_id');
                if(empty($room_ids)){
                    $is_empty  = true;
                }

            }
            if (isset($request['nick']) && ($request['nick'])) {
                $uid =Member::getUidByNick($request['nick']);
                if($uid)
                {
                    $room_ids =  mLiveRoom::selectByWhere(['uid' => $request['uid']],'room_id');
                }
                if(empty($room_ids)){
                    $is_empty  = true;
                }
            }
        }
        $column_room_ids  = [];
        if (isset($request['room_column']) && ($request['room_column'])) {
            $column_room_ids =  mLiveRoom::selectByWhere(['room_column' => $request['room_column']],'room_id');
            if(empty($column_room_ids)){
                $is_empty  = true;
            }
        }
        if($room_ids && $room_ids){
            if($request['room_column']){
                $room_ids = array_intersect($room_ids , $column_room_ids);
            }
            if($room_ids && is_array($room_ids)){
                $response['room_id'] = $room_ids;
            }else{
                $is_empty  = true;

            }
        }elseif($column_room_ids && is_array($column_room_ids)){
            $response['room_id'] = $column_room_ids;
        }
         return [
            'is_empty' => $is_empty ,
            'condition' => $response
           ];
    }



    /*直播房间号
    *
    * */
    public function setContent(Request $request ,Content $content , $roomid)
    {
        Admin::style('.main-header {display:none;}');
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        Admin::script($script);
        $info = LiveRelaContent::getByWhere(['rela_status' => LiveRelaContent::STATUS_NORMAL,'room_id' => $roomid]);

        $info = $info ? : [];
        $info['room_id'] = $roomid;
        $info['obj_id'] = $info['obj_id'] ? : '';
        $info['id'] = $info['id'] ? : 0;
        $form = new Form($info);
        $form->hidden('room_id' );
        $form->hidden('id' );
        $form->text('obj_id' , '整屋id')->required();
        $form->disableReset();
        $form->action('/admin/live/index/backList/addContent');
        return $content->row($form->render());
    }



    /*添加直播房间号
     *
     * */
    public function addContent(Request $request)
    {
        $request = $request->all();
        $aid = trim($request['obj_id']);
        $info = dbArticle::getBatchArticleByIds([$aid]);
        $room_id = $request['room_id'];
        if(empty($info) || empty($room_id)){
            $error = new MessageBag([
                'title' => '参数错误'
            ]);
            return redirect('/admin/live/index/backList/setContent/'.$room_id."?code=0")->with(compact('error'));

        }
        $id = $request['id'] ? : 0;
        if($id){
            $update_data = [
                'obj_id' => $aid ,
                'rela_status' => LiveRelaContent::STATUS_NORMAL,
                'admin_id' => Admin::user()->id,
            ];
            LiveRelaContent::updateData($update_data , ['id' => $id]);
        }else{
            $insert_data = [
                'obj_id' => $aid,
                'obj_type' => BlockType::TYPE_ARTICLE,
                'room_id' => $room_id,
                'admin_id' => Admin::user()->id,
                'rela_status' => LiveRelaContent::STATUS_NORMAL
            ];
            LiveRelaContent::insertData($insert_data);
        }
        LiveRelaContent::updateData(['rela_status' => LiveRelaContent::STATUS_DELETE] , ['room_id' => $room_id,'obj_id[!]'=> $aid]);
        LiveRelaContent::updateData(['rela_status' => LiveRelaContent::STATUS_DELETE] , ['room_id[!]' => $room_id ,'obj_id'=> $aid]);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/live/index/backList/setContent/'.$room_id."?code=1")->with(compact('success'));
    }


    /*删除精选
    * */
    public function delContent(Request $request ,$rela_id)
    {
        try{
            //删除精选
            $updata_data = [
                'rela_status' => LiveRelaContent::STATUS_DELETE,
                'admin_id' => Admin::user()->id
            ];
            LiveRelaContent::updateData($updata_data , ['id' => $rela_id]);
            $status= true ;
            $message = "操作成功";

        }catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return  response()->json(compact('status', 'message'));
    }


    public function edit(Request $request ,$cmd)
    {
        if($cmd == 'addContent'){
            $request = $request->all();
            $aid = trim($request['obj_id']);
            $info = dbArticle::getBatchArticleByIds([$aid]);
            $room_id = $request['room_id'];
            if(empty($info) || empty($room_id)){
                $error = new MessageBag([
                    'title' => '参数错误'
                ]);
                return redirect('/admin/live/index/backList/setContent/'.$room_id."?code=0")->with(compact('error'));

            }
            $id = $request['id'] ? : 0;
            if($id){
                $update_data = [
                    'obj_id' => $aid ,
                    'rela_status' => LiveRelaContent::STATUS_NORMAL,
                    'admin_id' => Admin::user()->id,
                ];
                LiveRelaContent::updateData($update_data , ['id' => $id]);
            }else{
                $insert_data = [
                    'obj_id' => $aid,
                    'obj_type' => BlockType::TYPE_ARTICLE,
                    'room_id' => $room_id,
                    'admin_id' => Admin::user()->id,
                    'rela_status' => LiveRelaContent::STATUS_NORMAL
                ];
                LiveRelaContent::insertData($insert_data);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/live/index/backList/setContent/'.$room_id."?code=1")->with(compact('success'));
        }

    }


    /*设置scirpt
    *
    * */
    private function setScript()
    {
        return <<<SCRIPT
       
        //删除
         $('.delcontent').unbind('click').click(function(){
            var id= $(this).data('id');

            
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/live/index/backList/delContent/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }


}